package com.framework.core.utils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * 扫描指定包和子包下面的xml文件
 */
public class SqlScanXMLUtils {

	public static List<File> getXMLFile(String xmlPath) throws ClassNotFoundException, IOException {

		// 总files
		ArrayList<File> allFiles = new ArrayList<File>();

		String[] paths = null;
		if (xmlPath.contains(",")) {
			paths = xmlPath.split(",");
		} else {
			paths = new String[] { xmlPath };
		}

		for (String string : paths) {
			Class<?> c = SqlScanXMLUtils.class;
			String path = string.replace('.', '/');
			Enumeration<URL> resources = c.getClassLoader().getResources(path);
			List<File> dirs = new ArrayList<File>();

			while (resources.hasMoreElements()) {
				URL resource = resources.nextElement();
				dirs.add(new File(resource.getFile()));
			}
			ArrayList<File> files = new ArrayList<File>();
			for (File directory : dirs) {
				files.addAll(findClasses(directory, string));
			}
			allFiles.addAll(files);
		}

		return allFiles;
	}

	private static List<File> findClasses(File directory, String packageName) throws ClassNotFoundException {
		List<File> files = new ArrayList<File>();
		if (!directory.exists()) {
			return files;
		}
		File[] allFiles = directory.listFiles();
		for (File file : allFiles) {
			if (file.isDirectory()) {
				files.addAll(findClasses(file, packageName + "." + file.getName()));
			} else if (file.getName().endsWith(".xml")) {
				files.add(file);
			}
		}
		return files;
	}

}
